﻿
import tornado
import tornado.web

import os
import openai
import time
import requests
import jwt
import zhconv
import json
import back_method
import datetime

sign_key ="lyb_test_2023"

class BaseHandler(tornado.web.RequestHandler):
    # blog.csdn.net/moshowgame 解决跨域问题
    def set_default_headers(self):
        self.set_header('Access-Control-Allow-Origin', '*')
        self.set_header('Access-Control-Allow-Headers', '*')
        self.set_header('Access-Control-Max-Age', 3600)
        self.set_header('Content-type', 'application/json')
        self.set_header('Access-Control-Allow-Methods', 'POST, GET,DELETE,PUT')
        # self.set_header('Access-Control-Allow-Methods', '*')
        self.set_header('Access-Control-Allow-Headers', 'Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE')
        # self.set_header("Access-Control-Allow-Origin", origin_url)
        # self.set_header("Access-Control-Allow-Credentials", "true")
        # 如果header中有多种信息请一定要加种headers，如果header中存在user-token，必须在下面加入user-token，即self.set_header("Access-Control-Allow-Headers", "x-requested-with,token,user-token")
        # self.set_header("Access-Control-Allow-Headers", "x-requested-with,token")

    def options(self):
        self.set_status(200)
        self.finish()


class login(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = tornado.escape.json_decode(self.request.body)

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        phone=None
        api_key=None
        try:
            user_name = data["user_name"]
            password = data["password"]
            
            now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

            #获取姓名
            select_result = back_method.login_user(user_name,password)
            if select_result!=None and select_result!=() and select_result!=[] and len(select_result)>0:
                status =True
                nick_name = select_result[0]["nick_name"]
                phone = select_result[0]["phone"]

                result["data"]["nick_name"] = select_result[0]["nick_name"]

                # 将 session_key 存储到数据结构中，并生成 JWT 令牌返回给客户端
                token = jwt.encode({'phone': phone,"now_time":now_time,"nick_name":nick_name}, sign_key, algorithm='HS256')

                result["data"]["token"] = str(token)
                result["data"]["nick_name"] = nick_name
                msg="成功"
                result["msg"] = msg
                result["success"] = True
                result["code"] = 200
            else:
                result["msg"] = "用户名或密码错误"

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)

#用户信息更新
class course_search(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = tornado.escape.json_decode(self.request.body)

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            word =None
            page_id =1
            page_number =10

            
            if "word" in data.keys():
                word = data["word"]
            if "page_id" in data.keys():
                page_id = int(data["page_id"])
            if "page_number" in data.keys():
                page_number = int(data["page_number"])
            
            select_result = back_method.get_course(word=word,page_id=page_id,page_number=page_number)
            count_number = back_method.get_course_total(word=word)
            for x in range(len(select_result)):
                if type(select_result[x]) ==dict and "date" in select_result[x].keys() and select_result[x]["date"]!=None:
                    select_result[x]["date"] = select_result[x]["date"].strftime('%Y-%m-%d')

            result["data"]["course_list"] = select_result
            result["data"]["total"] = count_number
            result["data"]["page_id"] = page_id
            result["data"]["page_number"] = page_number
            msg="成功"
            result["msg"] = msg
            result["success"] = True
            result["code"] = 200

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)



#课程信息更新
class course_update(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = tornado.escape.json_decode(self.request.body)

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            word =None
            page_id =0
            page_number =10
            course_id = data["course_id"]
            del(data["course_id"])
            search_sql ={"id":course_id}
            select_result = back_method.update_course(search_sql,data)
            # result["data"]["product_list"] = select_result
            msg="成功"
            result["msg"] = msg
            result["success"] = True
            result["code"] = 200

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)

#图片上传
class image_upload(BaseHandler):
 
    #获取表单内容
    def post(self,*args,**kwargs):
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}
        try:
            #获取表单中的数据，images就是对应的html中name值
            image=self.request.files['images']
            #得到一系列的数据，获取你想要的内容
            for imag in image:
                #图片文件名
                filename=imag.get('filename')
                #图片被转换后的字节内容
                body=imag.get('body')
                #获取的content_type
                content_type=imag.get('content_type')
 
                #获取绝对路径
                dir=os.path.join(os.getcwd(),'image',filename)
                #写入到文件目录中
                with open(dir,'wb')  as fw:
                    fw.write(body)
                
                result["code"] = 200
                result["msg"] = "success"
                result["success"] = True

        except Exception as e:
            pass
        
        self.write(result)



#用户信息更新
class get_person(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = tornado.escape.json_decode(self.request.body)

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            word =None
            page_id =0
            page_number =10

            
            if "word" in data.keys():
                word = data["word"]
            if "page_id" in data.keys():
                page_id = int(data["page_id"])
            if "page_number" in data.keys():
                page_number = int(data["page_number"])
            
            select_result = back_method.get_person(word=word,page_id=page_id,page_number=page_number)
            for x in range(len(select_result)):
                if type(select_result[x]) ==dict and "date" in select_result[x].keys() and select_result[x]["date"]!=None:
                    select_result[x]["date"] = select_result[x]["date"].strftime('%Y-%m-%d')
            print(select_result)
            result["data"]["person_list"] = select_result
            msg="成功"
            result["msg"] = msg
            result["success"] = True
            result["code"] = 200

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)


#课程信息更新
class person_update(BaseHandler):

    def post(self, *args, **kwargs):

        msg="fail"
        #主数据类型
        data_type =0
        data = tornado.escape.json_decode(self.request.body)

        in_message = ""
        
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        api_key=None

        try:
            word =None
            page_id =0
            page_number =10
            person_id = data["person_id"]
            del(data["course_id"])
            search_sql ={"id":person_id}
            select_result = back_method.update_course(search_sql,data)
            # result["data"]["product_list"] = select_result
            msg="成功"
            result["msg"] = msg
            result["success"] = True
            result["code"] = 200

        except Exception as e:
            # print(e)
            result["msg"] = str(e)
            pass

        self.write(result)

class image_read(BaseHandler):

    def get(self, *args, **kwargs):
        result = {}
        result["code"] = 400
        result["msg"] = "Fail"
        result["success"] = False
        result["data"]={}

        try:
            msg="fail"
            imagename = self.get_argument('image')
            # imagename = "课程头图.jpg"
            if imagename.endswith('.jpg'):

                with open(r'image/{}'.format(imagename), 'rb') as f:
                    image = f.read()
                    # self.render(image)
                    self.write(image)
                    return self.set_header("Content-type", "image/jpg")
                
        except Exception as e:
            msg=e
            result["msg"] = msg
            pass
        
        self.write(result)



class PictureHandler(BaseHandler):
    def get(self):
        source_path = r'image'
        id = self.get_argument('id')
        if id.endswith('.jpg'):
            pic = open(source_path + r'/' + id, 'rb')
            pics = pic.read()
            self.write(pics)
            self.set_header("Content-type", "image/png")


application = tornado.web.Application([
    (r"/api/zhiku/back/login", login),
    (r"/api/zhiku/back/course_search", course_search),
    (r"/api/zhiku/back/course_update", course_update),
    (r"/api/zhiku/back/person_search", get_person),
    (r"/api/zhiku/back/person_update", person_update),
    ("/api/zhiku/back/image_upload",image_upload),
    ("/api/zhiku/back/image_read",image_read),
    ("/api/zhiku/back/pic",PictureHandler)
])

# 问题
if __name__ == '__main__':
    # threading.Thread(target=get_pid.main2,).start()
    # 将socket对象添加到select或epoll中
    application.listen(8211)
    # 3. 将select或epoll开始死循环 While True:
    tornado.ioloop.IOLoop.instance().start()

















































